/**
 * @title: PortalEntryActivity.java
 * @package com.sinoglobal.ningxia.activity.portal
 * @description: myTask(用一句话描述该文件做什么)
 * @author qiwx
 * @date 2014-11-13 上午9:39:22
 */
package com.sinoglobal.ningxia.activity.portal;

import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.telephony.TelephonyManager;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.JsResult;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebSettings.PluginState;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.luck.picture.lib.model.FunctionConfig;
import com.luck.picture.lib.model.LocalMediaLoader;
import com.luck.picture.lib.model.PictureConfig;
import com.orhanobut.logger.Logger;
import com.sinoglobal.ningxia.R;
import com.sinoglobal.ningxia.activity.base.BaseActivity;
import com.sinoglobal.ningxia.frame.FlyApplication;
import com.sinoglobal.ningxia.http.ConnectionUtil;
import com.sinoglobal.ningxia.utils.SharedPreferenceUtil;
import com.sinoglobal.ningxia.utils.TextUtil;
import com.sinoglobal.ningxia.utils.UriUtils;
import com.yalantis.ucrop.entity.LocalMedia;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @author qiwx
 * @title: PortalEntryActivity.java
 * @package com.sinoglobal.ningxia.activity.portal
 * @description: 门户入口
 * @date 2014-11-13 上午9:39:22
 */
public class PortalEntryActivity extends BaseActivity {
    private static final int REQUEST_CODE = 1024;//打开图片选择器
    private WebView wvProtry;// 微门户会议签到入口
    private String mUrl = "";
    private String ip = "";
    private ProgressBar pb;
    private TextView noData;
    private String index;// 首次进入设置为首页
    private int tag;// tag 为1代表是签到，tag为0代表通讯录
    private ConnectivityManager connectivityManager;
    private NetworkInfo info;
    ValueCallback<Uri[]> mFilePathCallback;
    ValueCallback<Uri> mUploadFile;
    private Button bt_choice_one;
    private Button bt_choice_two;
    private Button bt_choice_three;
    private Button bt_cancel;
    private Dialog chooseDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        isTemplate = false;
        super.onCreate(savedInstanceState);
        setContentView(R.layout.protal_entry_activity);
        openChenJInShi();//开启沉浸式
        Intent get = getIntent();
        tag = get.getIntExtra("tag", 0);
        try {
            ip = getIP();
        } catch (Exception e) {
            e.printStackTrace();
            ip = "";
        }
        init();
        getData();
        IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(mReceiver, filter);
        // getNativeIp();
//        initDialog();
    }

    private void initDialog() {
        View dialog_choose = getLayoutInflater().inflate(R.layout.dialog_choose, null);
        bt_choice_one = (Button) dialog_choose.findViewById(R.id.bt_choice_one);
        bt_choice_one.setText("视频");
        bt_choice_two = (Button) dialog_choose.findViewById(R.id.bt_choice_two);
        bt_choice_two.setVisibility(View.GONE);
        bt_choice_three = (Button) dialog_choose.findViewById(R.id.bt_choice_three);
        bt_choice_three.setText("相册");
        bt_cancel = (Button) dialog_choose.findViewById(R.id.bt_cancel);
        chooseDialog = new Dialog(this, R.style.Theme_dialog);
        chooseDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {

            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                Logger.i("Dialog的返回监听");
                if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
                    return true;
                }
                return false;
            }
        });
        setReSetDialog(dialog_choose, chooseDialog);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mReceiver);
    }

    private BroadcastReceiver mReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {

                connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
                info = connectivityManager.getActiveNetworkInfo();
                if (info == null)
                    return;
                NetworkInfo.State state = info.getState();
                if (state == NetworkInfo.State.CONNECTED && info.isAvailable()) {
                    String name = getIP();
                    try {
                        if (!ip.equals(name)) {
//                    		 Log.d("mark", getIP());
                            ip = name;
                            getData();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
            }
        }
    };

    private String getIP() {
        WifiManager wifiService = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
        WifiInfo wifiinfo = wifiService.getConnectionInfo();
        return intToIp(wifiinfo.getIpAddress());
    }

    private String intToIp(int i) {

        return (i & 0xFF) + "." + ((i >> 8) & 0xFF) + "." + ((i >> 16) & 0xFF) + "." + (i >> 24 & 0xFF);
    }

    private void getData() {
        if (TextUtil.stringIsNull(FlyApplication.userId)) {
            mUrl = ConnectionUtil.PORTAL_ENTRY;
        } else {

            String phone = SharedPreferenceUtil.getString(PortalEntryActivity.this, "username");
            String pwd = SharedPreferenceUtil.getString(mActivity, "autoPwd");
            TelephonyManager telephonyManager = (TelephonyManager) this.getSystemService(mActivity.TELEPHONY_SERVICE);
            String imei = telephonyManager.getDeviceId();
            switch (tag) {
                case 0:
                    mUrl = ConnectionUtil.PORTAL_ENTRY + phone + "&pass=" + pwd + "&mime=" + imei + "&ip=" + ip;
                    break;
                case 1:
                    mUrl = ConnectionUtil.PORTAL_CONTACTS + phone + "&pass=" + pwd + "&mime=" + imei + "&ip=" + ip;
                    break;
            }

            Logger.i(mUrl);
        }
        // mUrl = ConnectionUtil.PORTAL_ENTRY + "15595113131";
        /*
         * Intent intent = new Intent();
		 * intent.setAction("android.intent.action.VIEW"); Uri content_url =
		 * Uri.parse(mUrl); intent.setData(content_url); startActivity(intent);
		 */

        wvProtry.loadUrl(mUrl);
        wvProtry.setWebViewClient(new WebViewClient() {
            public boolean shouldOverrideUrlLoading(WebView view, String url) { // 重写此方法表明点击网页里面的链接还是在当前的webview里跳转，不跳到浏览器那边
                if (url == null)
                    return true;
                if (url.contains("tel")) {
                    url = url.replace("tel://", "");
                    Intent call_intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + url));
                    call_intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    if (call_intent != null) {
                        startActivity(call_intent);
                    }
                } else if (url.contains("web://close")) {
                    finish();
                } else {
                    view.loadUrl(url);
                }
                return true;
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                noData.setVisibility(View.GONE);
            }

            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                super.onReceivedError(view, errorCode, description, failingUrl);
                wvProtry.setVisibility(View.GONE);
                noData.setVisibility(View.VISIBLE);
            }

        });
        wvProtry.setWebChromeClient(new WebChromeClient() {

            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
                if (newProgress < 100) {
                    if (pb.getVisibility() == View.GONE)
                        pb.setVisibility(View.VISIBLE);

                } else {
                    pb.setVisibility(View.GONE);
                }
            }

            @Override
            public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
                AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext());
                builder.setTitle("提示").setMessage(message).setPositiveButton("确定", null);
                builder.setCancelable(false);
                AlertDialog dialog = builder.create();
                dialog.show();
                result.confirm();
                return true;
            }

            @Deprecated
            public void openFileChooser(ValueCallback<Uri> uploadFile, String acceptType, String capture) {
                mUploadFile = uploadFile;
                Logger.i("openFileChooser4.1++");
                //                //打开图片选择器
                // 先初始化参数配置，在启动相册
                FunctionConfig functionConfig = new FunctionConfig();
                functionConfig.setType(LocalMediaLoader.TYPE_IMAGE);//图片还是视频
//                functionConfig.setMaxSelectNum(9);//最多数量
                functionConfig.setSelectMode(FunctionConfig.MODE_SINGLE);//单选/多选
                functionConfig.setShowCamera(false);//是否显示摄像头
                functionConfig.setThemeStyle(ContextCompat.getColor(PortalEntryActivity.this, R.color.red600));//设置主题颜色
                functionConfig.setEnableCrop(false);//禁止裁剪
                PictureConfig.init(functionConfig);
                PictureConfig.getPictureConfig().openPhoto(PortalEntryActivity.this, resultCallback);
            }

            @Override
            public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
                mFilePathCallback = filePathCallback;
//                //打开图片选择器
                // 先初始化参数配置，在启动相册
                FunctionConfig functionConfig = new FunctionConfig();
                functionConfig.setType(LocalMediaLoader.TYPE_IMAGE);//图片还是视频
                functionConfig.setMaxSelectNum(9);//最多数量
                functionConfig.setSelectMode(FunctionConfig.MODE_MULTIPLE);//单选/多选
                functionConfig.setShowCamera(false);//是否显示摄像头
                functionConfig.setThemeStyle(ContextCompat.getColor(PortalEntryActivity.this, R.color.red600));//设置主题颜色
                functionConfig.setEnableCrop(false);//禁止裁剪
                PictureConfig.init(functionConfig);
                PictureConfig.getPictureConfig().openPhoto(PortalEntryActivity.this, resultCallback);
                return true;
            }
        });
    }


    private void init() {
        wvProtry = (WebView) findViewById(R.id.wv_entry);
        pb = (ProgressBar) findViewById(R.id.mProgress);
        noData = (TextView) findViewById(R.id.web_nodata);
        wvProtry.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);// 取消滚动条
        WebSettings sets = wvProtry.getSettings();
        sets.setDomStorageEnabled(true);
        sets.setPluginState(PluginState.ON);
        sets.setJavaScriptEnabled(true);

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // if (keyCode == KeyEvent.KEYCODE_BACK && wvProtry.canGoBack() &&
        // wvProtry.getUrl().contains("index")) {
        if (keyCode == KeyEvent.KEYCODE_BACK && wvProtry.canGoBack()) {
            wvProtry.goBack();// 返回前一个页面
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    /**
     * 图片回调方法
     */
    private PictureConfig.OnSelectResultCallback resultCallback = new PictureConfig.OnSelectResultCallback() {
        @Override
        public void onSelectSuccess(List<LocalMedia> resultList) {
            Logger.i("图片回调:" + resultList.size());
            final ArrayList<Uri> uriArrayList = new ArrayList<>();
            Iterator<LocalMedia> iterator = resultList.iterator();
            while (iterator.hasNext()) {
                LocalMedia localMedia = iterator.next();
                String path = localMedia.getPath();

                Uri parse = UriUtils.getImageContentUri(PortalEntryActivity.this, path);
                Logger.i("图片路径:" + path + "**URI:" + parse);
                uriArrayList.add(parse);
            }
            int size = uriArrayList.size();
            Uri[] uris = (Uri[]) uriArrayList.toArray(new Uri[size]);
            if (mFilePathCallback != null) {
                mFilePathCallback.onReceiveValue(uris);
                mFilePathCallback = null;
            } else if (mUploadFile != null) {
                mUploadFile.onReceiveValue(uris[0]);
                mUploadFile = null;
            }

        }

    };

    @Override
    protected void onResume() {
        super.onResume();
        Logger.i("图片onResume");
        if (mFilePathCallback != null) {
            mFilePathCallback.onReceiveValue(new Uri[]{});
            mFilePathCallback = null;
        }
        if (mUploadFile != null) {
            mUploadFile.onReceiveValue(null);
            mUploadFile = null;
        }

    }

    /**
     * 对话框
     *
     * @param view
     * @param dialog
     */
    public void setReSetDialog(View view, Dialog dialog) {
        dialog.setContentView(view, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        Window window = dialog.getWindow();
        // 设置显示动画
        window.setWindowAnimations(R.style.dialog_menu_animstyle);
        WindowManager.LayoutParams wl = window.getAttributes();
        wl.x = 0;
        wl.y = getWindowManager().getDefaultDisplay().getHeight();
        // 以下这两句是为了保证按钮可以水平满屏
        wl.width = ViewGroup.LayoutParams.MATCH_PARENT;
        wl.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        // 设置显示位置
        dialog.onWindowAttributesChanged(wl);
        // 设置点击外围解散
        dialog.setCanceledOnTouchOutside(false);
    }
}
